import json
import os.path
import uuid
from os.path import join, splitext

import sumolib

import scene
import rou.constants as rc
import sumo_utils
from rou._config_item import ConfigItem
from utils.common_util import update_file


class RouConfig:
    cfg_name = rc.DEFAULT_CFG_NAME

    def __init__(self):
        self.config_name_map = dict()
        self._config_list = []
        global config_name_map
        # 将名字对应的字典存入_config配置中
        # self._config_name = dict()
        for _, _, files in os.walk(rc.DEFAULT_PATH):
            for file_name in files:
                # 判断文件后缀是否为.sumocfg
                if file_name.endswith(rc.CONFIG_TASK_SUFFIX):
                    # 将文件名存入字典中 截取.sumocfg之前的名字
                    last_sumocfg_index = file_name.rfind(".task")
                    if last_sumocfg_index != -1:
                        name = file_name[:last_sumocfg_index]
                        cfg_path = join(rc.DEFAULT_PATH, file_name)
                        with open(cfg_path, "r", encoding="utf-8") as f:
                            data = f.read()
                        self.config_name_map[name] = data

                if file_name == self.cfg_name:
                    cfg_path = join(rc.DEFAULT_PATH, file_name)
                    config_item = ConfigItem(len(self._config_list) + 1, '', cfg_path)
                    self._config_list.append(config_item)
                    #                 添加自由路由
                    config_freeRoute = ConfigItem(len(self._config_list) + 1, '', cfg_path, route=str(uuid.uuid1()))
                    self._config_list.append(config_freeRoute)
        print(self._config_list)

    def get_all_config(self):
        return list(map(lambda x: x.to_dict(), self._config_list))

    def get_config_item(self, no: int):
        config = list(filter(lambda x: x['no'] == no, self._config_list))
        return config[0].to_dict() if config is not None and len(config) > 0 else {}

    def update_config(self, task_id, rou_id, config, operate):
        # 根据任务id 查询到对应的json文件(根据任务id查询到对应的json文件)
        task = self.config_name_map[task_id]
        if task is not None:
            # 根据rou_id 查询到对应的json文件
            # 获取task_id对应的json文件 0-新增,修改 1删除
            task_json = json.loads(task)
            task_list = []

            if operate == '0':
                for t in task_json:
                    # 修改默认属性
                    if config['code'] == '0':
                        if str(t['no']) == rou_id and rou_id == "2":
                            # 根据config 中的code码值 修改对应的配置
                            t['flag'] = '0'
                            # vehiclePoints=[]
                            # vehiclePoints.append(config['route'][0]['depart']['point'])
                            if 'route' in config:
                                result = config['route']
                                a = result[0]['id']
                                www = len(a)
                                if www == 0:
                                    # 新增路由
                                    # configItem=ConfigItem(t['no'],t['name'],'D:\\pythonproject\\changansumo\\CADXWCFZ_sumo\\webgl\\长安大学_openDrive_v0.sumocfg',r_type=1,route=str(uuid.uuid1()))
                                    route = sumo_utils.getFreeRoute(t['netPath'], str(uuid.uuid1()),
                                                                    config['route'][0]['depart']['point'], result)
                                    list_routes = t['route']
                                    for ww in list_routes:
                                        if len(ww['route']) == 0:
                                            list_routes.remove(ww)

                                    route[0]['arrive'] = route[0]['route'][-1]
                                    list_routes.append(route[0])
                                else:
                                    # 编辑路由
                                    route = sumo_utils.getFreeRoute(t['netPath'], result[0]['id'],
                                                                    config['route'][0]['depart']['point'], result)
                                    list_routes = t['route']
                                    for ww in list_routes:
                                        if ww['id'] == result[0]['id']:
                                            list_routes.remove(ww)
                                            route[0]['arrive'] = route[0]['route'][-1]
                                            list_routes.append(route[0])

                            # t['route']=route
                            # 修改默认的route
                        elif str(t['no']) == rou_id and rou_id == "1":
                            t['flag'] = '0'
                            if 'route' in config:
                                result = config['route']
                                a = result[0]['id']
                                for t_route in t['route']:
                                    if t_route['id'] == a:
                                        t_route['depart'] = result[0]['depart']
                        else:
                            t['flag'] = '1'
                    # 主路限速
                    elif config['code'] == '1':
                        if str(t['no']) == rou_id:
                            # 首先先获取到所有的原始文件中 就存在的数据
                            rateLimitingDict = dict()
                            if 'rateLimiting' in t['sceneInfo']:
                                rateLimitingDict = dict(map(lambda rl: (str(rl['id']), rl),
                                                            t['sceneInfo']['rateLimiting']))
                            for rateL in config['speedLimitList']:
                                if 'id' in rateL:
                                    if rateL['id'] in rateLimitingDict.keys():
                                        rate_json = {
                                            "id": rateL['id'],
                                            "areaPoints": rateL['areaPoints'],
                                            "speedLimitPoints": rateL['speedLimitPoints'],
                                            "speeds": rateL['speeds']
                                        }
                                        rateLimitingDict[rateL['id']] = rate_json
                                else:
                                    uid = str(uuid.uuid1())
                                    rate_json = {
                                        "id": uid,
                                        "areaPoints": rateL['areaPoints'],
                                        "speedLimitPoints": rateL['speedLimitPoints'],
                                        "speeds": rateL['speeds']
                                    }
                                    rateLimitingDict[uid] = rate_json
                            rateLimitingList = list(rateLimitingDict.values())
                            t['sceneInfo']['rateLimiting'] = rateLimitingList
                    # 施工区域
                    elif config['code'] == '2':
                        if str(t['no']) == rou_id:
                            accidentDict = dict()
                            if 'accident' in t['sceneInfo']:
                                accidentDict = dict(map(lambda rl: (str(rl['id']), rl), t['sceneInfo']['accident']))
                            for accident in config['accidentList']:
                                if 'id' in accident:
                                    if accident['id'] in accidentDict.keys():
                                        accident_json = {
                                            "id": accident['id'],
                                            "areaPoints": accident['areaPoints'],
                                            "status": accident['status']
                                        }
                                        accidentDict[accident['id']] = accident_json
                                else:
                                    uid = str(uuid.uuid1())
                                    accident_json = {
                                        "id": uid,
                                        "areaPoints": accident['areaPoints'],
                                        "status": accident['status']
                                    }
                                    accidentDict = dict()
                                    accidentDict[uid] = accident_json
                            accidentList = list(accidentDict.values())
                            t['sceneInfo']['accident'] = accidentList
                    # 应急车道
                    elif config['code'] == '3':
                        if str(t['no']) == rou_id:
                            emergencyLaneDict = dict()
                            if 'emergencyLane' in t['sceneInfo']:
                                emergencyLaneDict = dict(map(lambda rl: (str(rl['id']), rl),
                                                             t['sceneInfo']['emergencyLane']))
                            for emergency in config['emergencyLaneList']:
                                if 'id' in emergency:
                                    if emergency['id'] in emergencyLaneDict.keys():
                                        emergency_json = {
                                            "id": emergency['id'],
                                            "areaPoints": emergency['areaPoints'],
                                            "status": emergency['status']
                                        }
                                        emergencyLaneDict[emergency['id']] = emergency_json
                                else:
                                    uid = str(uuid.uuid1())
                                    emergency_json = {
                                        "id": uid,
                                        "areaPoints": emergency['areaPoints'],
                                        "status": emergency['status']
                                    }
                                    emergencyLaneDict[uid] = emergency_json
                            emergencyLaneList = list(emergencyLaneDict.values())
                            t['sceneInfo']['emergencyLane'] = emergencyLaneList
                    # 匝道管控
                    elif config['code'] == '4':
                        if str(t['no']) == rou_id:
                            rampControl_json = {
                                "rampControlNum": config['rampControlNum']
                            }
                            t['sceneInfo']['rampControl'] = rampControl_json
                    # 专用车道
                    elif config['code'] == '5':
                        if str(t['no']) == rou_id:
                            specialLaneDict = dict()
                            if 'specialLane' in t['sceneInfo']:
                                specialLaneDict = dict(map(lambda rl: (str(rl['id']), rl),
                                                           t['sceneInfo']['specialLane']))
                            for special in config['specialLaneList']:
                                if 'id' in special:
                                    if special['id'] in specialLaneDict.keys():
                                        special_json = {
                                            "id": special['id'],
                                            "areaPoints": special['areaPoints'],
                                            "status": special['status']
                                        }
                                        specialLaneDict[special['id']] = special_json
                                else:
                                    uid = str(uuid.uuid1())
                                    special_json = {
                                        "id": uid,
                                        "areaPoints": special['areaPoints'],
                                        "status": special['status']
                                    }
                                    specialLaneDict[uid] = special_json
                            specialLaneList = list(specialLaneDict.values())
                            t['sceneInfo']['specialLane'] = specialLaneList
                    # 编队车辆开关
                    elif config['code'] == '6':
                        if str(t['no']) == rou_id:
                            platoon_json = {
                                "status": config['status']
                            }
                            t['sceneInfo']['platoonSwitch'] = platoon_json
                    task_list.append(t)
                json_str = json.dumps(task_list, ensure_ascii=False)
                self.config_name_map[task_id] = json_str
                # json_str = json.dumps(task_list, ensure_ascii=False)

                # 将修改后的json文件写入到对应的文件中
                update_file(join(rc.DEFAULT_PATH, task_id + rc.CONFIG_TASK_SUFFIX), json_str)
            elif operate == '1':
                for t in task_json:

                    # 主路限速
                    if config['code'] == '1':
                        if str(t['no']) == rou_id:
                            rateLimitingDict = dict()
                            if 'rateLimiting' in t['sceneInfo']:
                                rateLimitingDict = dict(map(lambda rl: (str(rl['id']), rl),
                                                            t['sceneInfo']['rateLimiting']))
                            for rateL in config['speedLimitList']:
                                if 'id' in rateL and rateL['id'] in rateLimitingDict.keys():
                                    rateLimitingDict.pop(rateL['id'])
                            rateLimitingList = list(rateLimitingDict.values())
                            t['sceneInfo']['rateLimiting'] = rateLimitingList
                    # 施工区域
                    elif config['code'] == '2':
                        if str(t['no']) == rou_id:
                            accidentDict = dict()
                            if 'accident' in t['sceneInfo']:
                                accidentDict = dict(map(lambda rl: (str(rl['id']), rl), t['sceneInfo']['accident']))
                            for accident in config['accidentList']:
                                if 'id' in accident and accident['id'] in accidentDict.keys():
                                    accidentDict.pop(accident['id'])
                            accidentList = list(accidentDict.values())
                            t['sceneInfo']['accident'] = accidentList
                    # 应急车道
                    elif config['code'] == '3':
                        if str(t['no']) == rou_id:
                            emergencyLaneDict = dict()
                            if 'emergencyLane' in t['sceneInfo']:
                                emergencyLaneDict = dict(map(lambda rl: (str(rl['id']), rl),
                                                             t['sceneInfo']['emergencyLane']))
                            for emergency in config['emergencyLaneList']:
                                if 'id' in emergency and emergency['id'] in emergencyLaneDict.keys():
                                    emergencyLaneDict.pop(emergency['id'])
                            emergencyLaneList = list(emergencyLaneDict.values())
                            t['sceneInfo']['emergencyLane'] = emergencyLaneList
                    # 专用车道
                    elif config['code'] == '5':
                        if str(t['no']) == rou_id:
                            specialLaneDict = dict()
                            if 'specialLane' in t['sceneInfo']:
                                specialLaneDict = dict(map(lambda rl: (str(rl['id']), rl),
                                                           t['sceneInfo']['specialLane']))
                            for special in config['specialLaneList']:
                                if 'id' in special and special['id'] in specialLaneDict.keys():
                                    specialLaneDict.pop(special['id'])
                            specialLaneList = list(specialLaneDict.values())
                            t['sceneInfo']['specialLane'] = specialLaneList
                    elif config['code'] == '0':
                        # 自由路由删除
                        if 'route' in config:
                            result = config['route']

                            list_routes = t['route']
                            for ww in list_routes:
                                if ww['id'] == result[0]['id']:
                                    list_routes.remove(ww)

                    task_list.append(t)
                json_str = json.dumps(task_list, ensure_ascii=False)
                self.config_name_map[task_id] = json_str
                # 将修改后的json文件写入到对应的文件中
                update_file(join(rc.DEFAULT_PATH, task_id + rc.CONFIG_TASK_SUFFIX), json_str)
        else:
            return None
        return self.config_name_map[task_id]

    def get_config_name_map(self):
        return self.config_name_map
